package cn.meng.base.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.meng.base.service.LoginService;
import cn.meng.base.service.RegisterService;
import cn.meng.base.service.RoleService;
import cn.meng.base.vo.UserVo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;

@RestController
public class RegisterController {

    @Autowired
    RegisterService registerService;
    @Autowired
    LoginService loginService;
    @Autowired
    RoleService roleService;

    @RequestMapping("/register")
    public String register(@RequestBody String parms){
        HashMap<Object, Object> resultMessage = new HashMap<>();
        JSONObject jsonObject = JSONUtil.parseObj(parms);
        String pk_user=UUID.randomUUID().toString().replace("-","").substring(0,20).toUpperCase();
        String username = (String) jsonObject.get("username");
        String password = (String) jsonObject.get("password");
        String email = (String) jsonObject.get("email");
        String pk_role=roleService.queryRoot();
        UserVo user = new UserVo(pk_user, username, password, email, 1,pk_role);

            if(loginService.queryUser(username)==null){
                if(registerService.queryEmail(email)==null)
                {
                    registerService.addUser(user);
                    resultMessage.put("success",true);
                }
                else {
                    resultMessage.put("error","邮箱已被注册");
                }
            }
            else{
                resultMessage.put("error","用户名已存在");
            }

        return JSON.toJSONString(resultMessage);
    }
}
